package cn.com.w.redisson.controller;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {



    @Resource
    private RedissonClient redisson;

    @GetMapping("/")
    public String hello(){

        RLock rLock = redisson.getLock("redissonLock");
        try {
            boolean b = rLock.tryLock(1, TimeUnit.MILLISECONDS);
            if (b) {
                System.out.println(Thread.currentThread().getName() + "获取到锁");
                try {
                    Thread.sleep(60000L);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println(Thread.currentThread().getName() + "未获取到锁");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (rLock.isLocked()) {
                if (rLock.isHeldByCurrentThread()) {
                    System.out.println(Thread.currentThread().getName() + "释放锁");
                    rLock.unlock();
                }
            }
        }
        return "hello word";
    }
}
